package TalkChat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class TalkReceiver implements Runnable{
    DatagramSocket socket=null;
    private int port=8888;
    private String msgFrom;

    public TalkReceiver(int port, String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true){
            try {
                // prepare
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);
                // get data
                byte[] data = packet.getData();
                //data.length 会导致 receiveData 字符串中包含很多无效的空字节
                String receiveData = new String(data, 0, packet.getLength());
                System.out.println(msgFrom+"："+receiveData);
                // break
                if (receiveData.equals("exit")) {
                    break;
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        socket.close();

    }
}
